<?php
/**
 * 处理某天的拉卡拉对账数据
 * @author angl
 */

date_default_timezone_set("Asia/Shanghai");
set_time_limit(0);
if (isset($_SERVER['REQUEST_URI'])) {
    die('error');
}

if (!defined('API_ROOT_PATH')) {
    define('API_ROOT_PATH', dirname(__FILE__));
}

require(API_ROOT_PATH . '/common/common.php');
require(API_ROOT_PATH . '/../inc/Config.php');
require(API_ROOT_PATH . '/../inc/MysqliDb.php');

//初始化数据库链接
function init_db()
{
    $db = new MysqliDb ([
        'host' => MYSQLDB,
        'username' => MYSQLDB_USER,
        'password' => MYSQLDB_PWD,
        'db' => MYSQLDB_DATABASE,
        'port' => 3306,
        'prefix' => 'au_',
        'charset' => 'utf8'
    ]);
    return $db;
}


$db = init_db();


$day = $argv['1'];
if(empty($day)){
    echo "请输入指定日期";
    exit;
}

try {
    $bill_list = $db->where('deal_time', [$day . " 00:00:00", $day . " 23:59:59"], 'BETWEEN')
        ->where('pay_result',1)
        ->where('third_party',1)
        ->get("recharge_log");
    if(empty($bill_list)){
        logUtil("No bills {$day}");
        exit;
    }
    $ret = $db->where('create_date',$day)->getOne('lakala_bill');
    if(!empty($ret)){
        $db->where('create_date',$day)->update('lakala_bill',[
            'settlement_money' => 0,
            'amount' => 0,
            'poundage' => 0,
        ]);
    }else{
        $db->insert('lakala_bill',['create_date'=>$day]);
    }
    foreach ($bill_list as $bill){
        $remark = json_decode($bill['remark'],true);
        $db->where('create_date',$day)->update('lakala_bill',[
            'settlement_money'=> $db->inc($bill['amount']),
            'amount'=>$db->inc(1),
            'poundage'=>$db->inc($remark['data']['orderFee'])
        ]);
        logUtil("dealer : {$bill['dealer_id']} at {$bill['deal_time']} charge {$bill['amount']} ");
    }
    logUtil("Today task finished");
    exit;
} catch (Exception $e) {
    logUtil($e->getCode() . ": " . $e->getMessage(), "ERROR");
    sleep(60);
}
